<template>
  <div id="tpl">
    <!-- 评论组件 -->
    <!-- 提交评论 -->
    <div id="postComment">
      <h3>提交评论</h3>
      <hr>
      <textarea name="name" placeholder="请输入评论内容" v-model.trim="postContent" @keyup.enter="postCommentInfo"></textarea>
      <mt-button type="primary" size="large" @click="postCommentInfo">发表评论</mt-button>
    </div>

    <!-- 展示评论 -->
    <div id="commentList">
      <h3>评论列表</h3>
      <hr>
      <div v-for="(item,index) in list" :key="index">
        <div class="title">
          <span>{{index+1}}楼</span>
          <span>{{item.user_name}}</span>
          <span>{{item.add_time | dateFmt('YYYY-MM-DD HH:mm:ss')}}</span>
        </div>
        <ul class="mui-table-view">
          <li class="mui-table-view-cell">{{item.content}}</li>
        </ul>
      </div>
    </div>
    <mt-button v-if="!isEnd" type="danger" size="large" plain @click="getmore">加载更多</mt-button>
    <mt-button v-if="isEnd" type="danger" size="large" plain>已到底</mt-button>
  </div>
</template>

<script>
  import common from '../../kits/common.js';
  import {Toast} from 'mint-ui';
  export default {
    props: ['id'],
    data(){
      return {
        postContent: '',
        pageindex: 1,
        list: [],
        isEnd: false
      };
    },
    created(){
      this.getComments();
    },
    methods: {
      // 发表评论
      postCommentInfo: function(){
        if(this.postContent.trim().length <= 0){
          Toast('评论内容不能为空，请输入评论后再次提交。');
        }
        var url = common.apidomain + '/api/postcomment/' + this.id;
        var options = {content: this.postContent}
        this.$http
            .post(url, options, {emulateJSON: true})
            .then(function(res){
            Toast(res.body.message);
            // this.postContent = '';
            // this.getComments();
            this.list.unshift({"user_name": "匿名用户", "add_time": new Date(), "content": this.postContent});
            this.postContent = '';
        });
      },
      // 获取评论
      getComments: function(){
        var url = common.apidomain + '/api/getcomments/' + this.id + '?pageindex=' + this.pageindex;
        this.$http.get(url).then(function(res){
          if(res.body.status != 0){
            Toast(res.body.message);
            return;
          }

          this.list = this.list.concat(res.body.message);
          if(res.body.message.length == 0){
            this.isEnd = true;
          }
        });
      },
      // 加载更多
      getmore: function(){
        this.pageindex++;
        this.getComments();
      }
    }
  }
</script>

<style scoped>
  #postComment {
    padding: 5px;
  }
  #commentList {
    padding: 5px;
  }
  #commentList .title {
    padding: 5px;
    background-color: rgba(0,0,0,.2);
  }

</style>
